package com.example.demo.demos.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author LH
 * @since 2025/9/9 11:18
 **/
public class PinyinUtils {
    /**
     * 获取字符串的拼音首字母
     *
     * @param chinese 中文字符
     * @return 简拼
     */
    public static String getFirstLetters(String chinese) {
        StringBuilder firstLetters = new StringBuilder();
        char[] chars = chinese.toCharArray();

        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        for (char c : chars) {
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]")) { // 中文字符
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        firstLetters.append(pinyinArray[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else { // 非中文字符直接保留
                firstLetters.append(c);
            }
        }
        return firstLetters.toString();
    }
}
